using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.ComponentModel;
using SiteECSWeb;
using System.IO;

/// <summary>
/// Summary description for MembershipUserBiz
/// </summary>
namespace SiteECSWeb
{
    [DataObject(true)]
    public class MembershipUserBiz
    {
        public MembershipUserBiz()
        {

        }

        #region SelectUsers
        static public int GetTotalNumberOfMembers()
        {
            MembershipUserCollection xx = Membership.GetAllUsers();
            return xx.Count;
        }
        [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
        static public List<MembershipUserWrapper> GetMemebers()
        {
            return GetMemebers(true, true, null,
                null, null);
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
        static public List<MembershipUserWrapper> GetMemebers
            (string RoleName, string sortData)
        {
            return GetMemebers(true, true, null, RoleName, sortData);
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
        static public List<MembershipUserWrapper> GetMemebers(bool approvalStatus,
            string RoleName, string sortData)
        {
            if (approvalStatus == true)
            {
                return GetMemebers(true, false, null, RoleName, sortData);
            }
            else
            {
                return GetMemebers(false, true, null, RoleName, sortData);
            }
        }

        [DataObjectMethodAttribute(DataObjectMethodType.Select, true)]
        static public List<MembershipUserWrapper> GetMemebers(bool retunAllApprovedUsers,
            bool returnAllNotApprovedUsers, string usernameToFind, string RoleName,
            string sortData)
        {

            List<MembershipUserWrapper> memberList = new
                List<MembershipUserWrapper>();

            if (!string.IsNullOrEmpty(usernameToFind))
            {
                int len = usernameToFind == null ? 0 : usernameToFind.Length;

                MembershipUserCollection muc = Membership.GetAllUsers();
                foreach (MembershipUser mUser in muc)
                {
                    //string[] xx = Roles.GetRolesForUser(mUser.UserName);
                    
                    string[] RolesNames = RoleName.Split(',');
                    foreach (string _roleName in RolesNames)
                    {
                        if (Roles.IsUserInRole(mUser.UserName, _roleName))
                        {
                            MembershipUserWrapper checkUser = memberList.Find(
                                    delegate(MembershipUserWrapper wrap)
                                    {
                                        return wrap.UserName == mUser.UserName;
                                    });
                            if (checkUser == null)
                            {
                                MembershipUserWrapper muw = new MembershipUserWrapper(mUser, _roleName);
                                int compareLength = Math.Min(len, muw.RelatedNameToUser.Length);
                                if (muw.RelatedNameToUser.Substring(0, compareLength).ToLower().
                                    Equals(usernameToFind.Substring(0, compareLength).ToLower()) &&
                                    muw.RelatedNameToUser.Length >= len)
                                {
                                    memberList.Add(muw);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MembershipUserCollection muc = Membership.GetAllUsers();

                foreach (MembershipUser mUser in muc)
                {
                    if ((retunAllApprovedUsers == true && mUser.IsApproved == true) ||
                        (returnAllNotApprovedUsers == true && mUser.IsApproved == false))
                    {
                        string[] RolesNames = RoleName.Split(',');
                        foreach (string _roleName in RolesNames)
                        {
                            if (Roles.IsUserInRole(mUser.UserName, _roleName))
                            {
                                MembershipUserWrapper checkUser = memberList.Find(
                                    delegate(MembershipUserWrapper wrap)
                                    {
                                        return wrap.UserName == mUser.UserName;
                                    });
                                if (checkUser == null)
                                {
                                    MembershipUserWrapper muw = new MembershipUserWrapper(mUser, _roleName);
                                    memberList.Add(muw);
                                }
                            }
                        }
                    }
                }
                if (string.IsNullOrEmpty(sortData))
                {
                    sortData = "UserName";
                }
                if (sortData.Length == 0)
                {
                    sortData = "UserName";
                }
                string sortDataBase = sortData;
                string descString = " DESC";
                if (sortData.EndsWith(descString))
                {
                    sortDataBase = sortData.Substring(0, sortData.Length - descString.Length);
                }
                Comparison<MembershipUserWrapper> comparison = null;

                switch (sortDataBase)
                {
                    case "UserName":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                return lhs.UserName.CompareTo(rhs.UserName);
                            });
                        break;
                    case "Email":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                if (string.IsNullOrEmpty(lhs.Email) ||
                                    string.IsNullOrEmpty(rhs.Email))
                                {
                                    return 0;
                                }
                                else
                                {
                                    return lhs.Email.CompareTo(rhs.Email);
                                }
                            });
                        break;
                    case "CreationDate":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                return lhs.CreationDate.CompareTo(rhs.CreationDate);
                            });
                        break;
                    case "IsApproved":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                return lhs.IsApproved.CompareTo(rhs.IsApproved);
                            });
                        break;
                    case "IsOnline":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                return lhs.IsOnline.CompareTo(rhs.IsOnline);
                            });
                        break;
                    case "LastLoginDate":
                        comparison = new Comparison<MembershipUserWrapper>(
                            delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                            {
                                return lhs.LastLoginDate.CompareTo(rhs.LastLoginDate);
                            });
                        break;
                    case "RelatedNameToUser":
                        comparison = new Comparison<MembershipUserWrapper>(
                           delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                           {
                               return lhs.RelatedNameToUser.CompareTo(rhs.RelatedNameToUser);
                           });
                        break;
                    default:
                        comparison = new Comparison<MembershipUserWrapper>(
                             delegate(MembershipUserWrapper lhs, MembershipUserWrapper rhs)
                             {
                                 return lhs.UserName.CompareTo(rhs.UserName);
                             }
                             );
                        break;
                }
                if (sortData.EndsWith("DESC"))
                {
                    memberList.Sort(comparison);
                    memberList.Reverse();
                }
                else
                {
                    memberList.Sort(comparison);
                }
            }
            return memberList;
        }
        #endregion

        #region InsertUsers

        [DataObjectMethodAttribute(DataObjectMethodType.Insert, true)]
        static public void Insert(string userName, string passWord, string Email,
            bool isAprroved, string comment, DateTime lastLockDate,
            string passwordQuestion, string passwordAnswer,
            DateTime creationDate, DateTime lastActivityDate, bool isLockedOut,
            DateTime lastLoginDate, bool isOnline, DateTime lastPasswordChangedDate,
            string providerName)
        {
            MembershipCreateStatus status;
            Membership.CreateUser(userName, passWord, Email,
                passwordQuestion, passwordAnswer, isAprroved, out status);
            if (status != MembershipCreateStatus.Success)
            {
                throw new ApplicationException(status.ToString());
            }
            MembershipUser mu = Membership.GetUser(userName);
            mu.Comment = comment;
            //modified by me 2009
            //MembershipUserWrapper mmmm = Membership.GetUser(userName);
            //mmmm.Comment = comment;
            //Membership.UpdateUser(mmmm);
            Membership.UpdateUser(mu);
        }

        #endregion

        #region UpdateUsers

        [DataObjectMethod(DataObjectMethodType.Update, true)]
        static public void Update(string userName, string email, bool isApproved,
            string comment, DateTime lastActivityDate, DateTime lastLoginDate)
        {
            bool dirtyFlag = false;
            MembershipUser mu = Membership.GetUser(userName);

            if (mu.Comment == null || mu.Comment.CompareTo(comment) != 0)
            {
                dirtyFlag = true;
                mu.Comment = comment;
            }
            if (mu.Email == null || mu.Email.CompareTo(email) != 0)
            {
                dirtyFlag = true;
                mu.Email = email;
            }
            if (mu.IsApproved != isApproved)
            {
                dirtyFlag = true;
                mu.IsApproved = isApproved;
            }
            if (dirtyFlag == true)
            {
                Membership.UpdateUser(mu);
            }
        }
        [DataObjectMethod(DataObjectMethodType.Update, false)]
        static public void Update(string userName, bool isApproved)
        {
            bool dirtyFlag = false;
            MembershipUser mu = Membership.GetUser(userName);
            if (mu.IsApproved != isApproved)
            {
                dirtyFlag = true;                
                mu.IsApproved = isApproved;
            }
            if (dirtyFlag == true)
            {
                Membership.UpdateUser(mu);
            }
        }

        #endregion

        #region DeleteUsers

        [DataObjectMethod(DataObjectMethodType.Delete, true)]
        static public void Delete(string userName, string roleName)
        {
            bool flagdirty = false;
            MembershipUser mUser = Membership.GetUser(userName);
            switch (roleName.Trim())
            {
                case "Companies":
                case "NewUsers":
                    LcompanyBLL _lCompanyAPI = new LcompanyBLL();
                    EcsSiteDS.LcompanyDataTable _lcompanyTab =
                        _lCompanyAPI.GetLcompanyByCompEmail(mUser.Email);
                    if (_lcompanyTab.Count > 0)
                    {
                        EcsSiteDS.LcompanyRow _lcompanyRow = _lcompanyTab[0];
                        if (!_lcompanyRow.IsComp_logoPathNull())
                        {
                            System.IO.File.Delete(HttpContext.Current.Server.
                                MapPath(Globals.Settings.UploadInfo.RootAttachFolder
                                + _lcompanyRow.Comp_logoPath));
                        }

                        flagdirty =
                            _lCompanyAPI.DeleteLcomapny(_lcompanyRow.Comp_id);
                    }
                    break;
                case "ECSInternal":
                case "NewEcs":
                case "AdminSystem":
                case "SysAdmin":
                    //If you want to delete employee data profile, you could uncomment this,//
                    //EcsEmployeeBLL _empAPI = new EcsEmployeeBLL();
                    //EcsSiteDS.EcsEmployeeDataTable _empTab =
                    //    _empAPI.GetEcsEmployeeByEmpEmail(mUser.Email);
                    //if (_empTab.Count > 0)
                    //{
                    //    EcsSiteDS.EcsEmployeeRow _empRow = _empTab[0];
                    //    flagdirty =
                    //        _empAPI.DeleteEcsEmployee(_empRow.Ecsemp_id);
                    //}
                    break;
                case "Departments":
                    break;
                case "PublicPersons":
                    break;
                default:
                    break;
            }
            if (mUser != null || flagdirty)
            {
                Membership.DeleteUser(userName, true);
            }
        }

        #endregion
    }
}

